package cn.schoolwow.quickdao.module.database.dql.response.service;

import cn.schoolwow.quickdao.module.database.dql.parent.domain.QueryContext;
import cn.schoolwow.quickdao.module.database.dql.response.flow.common.SetConditionParameterFlow;
import cn.schoolwow.quickdao.module.database.parent.domain.ResultSetConsumer;
import cn.schoolwow.quickdao.module.database.parent.flow.executor.ExecuteQueryConnectionFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.sql.ResultSet;

public class GetCountFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        setStatement(flowContext);
        flowContext.executeFlowList(new SetConditionParameterFlow());
        executeStatement(flowContext);
    }

    @Override
    public String name() {
        return "根据查询条件查询记录个数";
    }

    private void setStatement(FlowContext flowContext) {
        QueryContext queryContext = (QueryContext) flowContext.checkData("queryContext");

        StringBuilder sqlBuilder = new StringBuilder("select count(1) from (");
        sqlBuilder.append(queryContext.select);
        sqlBuilder.append(queryContext.from);
        sqlBuilder.append(queryContext.join);
        sqlBuilder.append(queryContext.where);
        sqlBuilder.append(queryContext.groupBy);
        sqlBuilder.append(queryContext.having);
        sqlBuilder.append(") foo");
        flowContext.putTemporaryData("sql", sqlBuilder.toString());
    }

    private void executeStatement(FlowContext flowContext) throws Exception {
        flowContext.startFlow(new ExecuteQueryConnectionFlow())
                .putTemporaryData("name", "查询记录个数")
                .putReturnData("resultSetConsumer",new ResultSetConsumer() {
                    @Override
                    public void consumeResultSet(ResultSet resultSet) throws Exception {
                        if(resultSet.next()){
                            flowContext.putData("count", resultSet.getLong(1));
                        }
                    }
                })
                .execute();
    }

}
